package com.bort.system.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bort.system.model.Category;
import com.bort.system.model.Goods;
import com.bort.system.model.vo.GoodsVo;
import com.bort.system.service.GoodsService;
import com.bort.system.utils.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/goods")
public class AdminGoodsController {

    @Resource
    GoodsService goodsService;

    @RequestMapping("/list")
    public Result<Page<GoodsVo>> getGoodsList(
            @RequestParam(value = "current", defaultValue = "1") Integer page,
            @RequestParam(value = "rowSize", defaultValue = "12") Integer rowSize,
            @RequestParam(value = "goodsName",required = false)String goodsName,
            @RequestParam(value = "categoryId",required = false)Integer categoryId
    ) {

        Page<GoodsVo> pager = new Page<>();
        pager.setCurrent(page);
        pager.setSize(rowSize);
        Map<String,Object> map = new HashMap<>();
        map.put("goodsName",goodsName);
        map.put("categoryId",categoryId);
        return goodsService.getGoodsList(pager,map);
    }

    @RequestMapping(value = "/load",method = RequestMethod.GET)
    public Result<Goods> loadGoods(
            @RequestParam(value = "categoryId",required = false)Integer categoryId
    ) {
        List<Goods> list = goodsService.loadGoodsByCategoryId(categoryId);
        return Result.success(list);
    }


    @RequestMapping("/add")
    public Result<Goods> addCategory(@RequestBody Goods goods){
        if(goods == null){
            return Result.error("数据有误");
        }
        boolean adding = goodsService.addGoods(goods);
        return Result.success("新增成功");
    }

    @RequestMapping("/update")
    public Result<Goods> updateCategory(@RequestBody Goods goods){
        if(goods == null){
            return Result.error("数据有误");
        }
        boolean updating = goodsService.updateGoods(goods);
        return Result.success("修改成功");
    }


    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public Result<Goods> updateCategory(@RequestParam("id") Integer id){
        if(id == null){
            return Result.error("数据有误");
        }
        boolean updating = goodsService.deleteGoods(id);
        return Result.success("删除成功");
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Result upload(@RequestParam(value = "file",required = false) MultipartFile file){
        return goodsService.upload(file);
    }
}
